# Title: Measuring Interethnic Marriage in Africa
# Author: Branden Bohrnsen, bohrnsen@umich.edu
# Date: 1/30/2026
# Description: Master script to run the complete analysis pipeline sequentially.

library(here)

here::i_am("00_run_all.R")

scripts <- c(
  "01_cleaning.R",
  "02_diversity.R",
  "03_observed_rates.R",
  "04_adjusted_for_elf.R",
  "05_adjusted_for_exposure.R",
  "06_figures.R",
  "07_dhs.R",
  "08_appendix.R",
  "09_appendix_tables.R"
)

run_script <- function(script_name) {
  cat("\n")
  cat(paste(rep("=", 80), collapse = ""), "\n")
  cat("Running:", script_name, "\n")
  cat(paste(rep("=", 80), collapse = ""), "\n")

  script_path <- here(script_name)

  if (!file.exists(script_path)) {
    stop(paste("Script not found:", script_path))
  }

  start_time <- Sys.time()

  tryCatch({
    source(script_path, echo = FALSE)
    end_time <- Sys.time()
    elapsed <- difftime(end_time, start_time, units = "secs")

    cat("\n")
    cat("✓ Completed:", script_name, "\n")
    cat("  Time elapsed:", round(elapsed, 2), "seconds\n")

    return(TRUE)

  }, error = function(e) {
    cat("\n")
    cat("✗ ERROR in", script_name, "\n")
    cat("  Error message:", conditionMessage(e), "\n")

    stop(paste("Pipeline failed at:", script_name))
  })
}

cat("\n")
cat(paste(rep("#", 80), collapse = ""), "\n")
cat("# INTERETHNIC MARRIAGE IN AFRICA - ANALYSIS PIPELINE\n")
cat(paste(rep("#", 80), collapse = ""), "\n")
cat("\n")
cat("Project directory:", here(), "\n")
cat("Start time:", format(Sys.time(), "%Y-%m-%d %H:%M:%S"), "\n")
cat("Number of scripts to run:", length(scripts), "\n")

pipeline_start <- Sys.time()

for (script in scripts) {
  run_script(script)
}

pipeline_end <- Sys.time()
total_elapsed <- difftime(pipeline_end, pipeline_start, units = "mins")

cat("\n")
cat(paste(rep("#", 80), collapse = ""), "\n")
cat("# PIPELINE COMPLETE\n")
cat(paste(rep("#", 80), collapse = ""), "\n")
cat("\n")
cat("All scripts executed successfully!\n")
cat("Total time elapsed:", round(total_elapsed, 2), "minutes\n")
cat("End time:", format(Sys.time(), "%Y-%m-%d %H:%M:%S"), "\n")
cat("\n")
cat("Output directories:\n")
cat("  - Cleaned data: data/clean/\n")
cat("  - Intermediate results: out/inter/\n")
cat("  - Final results: out/final/\n")
cat("  - Figures: (displayed in console/RStudio)\n")
cat("\n")
